<template>
  <div>
    <van-field
      v-model="pickVal"
      right-icon="arrow"
      :label="label"
      label-align="top"
      :readonly="true"
      :placeholder="placeholder"
      :rules="[{ required: true, message: ruleMessage }]"
      @click="isShowPop = true"
    />
    <van-popup v-model:show="isShowPop" position="bottom" round>
      <van-search
        v-model="searchValue"
        shape="round"
        placeholder="请输入搜索关键词"
        @update:model-value="onSearch"
      />
      <van-picker :columns="selectList" @confirm="onConfirm" @cancel="onCancel" />
    </van-popup>
  </div>
</template>

<script setup>
const pickVal = defineModel()
const props = defineProps({
  label: {
    type: String,
    required: true
  },
  placeholder: {
    type: String,
    required: true
  },
  ruleMessage: {
    type: String,
    required: true
  },
  // 传入的list必须是响应式数组，而且初始值为空
  list: {
    type: Array,
    required: true
  }
})
const allList = computed(() => props.list)
// 输入搜索关键字后的列表
const selectList = ref([])
watch(allList, (newVal) => {
  selectList.value = newVal
})

// 是否显示客户单位popup
const isShowPop = ref(false)
// 搜索关键字
const searchValue = ref('')
// 搜索
const onSearch = (search) => {
  // console.log(search)
  if (search === '') {
    // 清空搜索关键字后，获取所有的内容
    selectList.value = allList.value
  } else {
    selectList.value = allList.value.filter((item) => {
      return item.text.includes(search)
    })
  }
}
// 确认后，给表单添加上选的值
const onConfirm = async (option) => {
  console.log(option)
  pickVal.value = option.selectedOptions[0]?.text
  isShowPop.value = false
}
// 关闭弹窗
const onCancel = () => {
  isShowPop.value = false
}
</script>

<style lang="scss" scoped></style>
